package com.mrx.tunnel.handler;

import com.mrx.tunnel.constants.SqlType;
import com.mrx.tunnel.constants.TunnelConstants;
import com.mrx.tunnel.model.Pair;
import com.mrx.tunnel.utils.TunnelUtils;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Mr.X
 * @since 2024/9/1 08:19
 */
@Service
public class Sqlite3Handler implements ISqlHandler {

    private static final String VERSION = "3.46.1.0";

    /**
     * 处理 sql 操作
     *
     * @param action  操作类型
     * @param dbFile  数据库文件
     * @param queries 查询语句
     * @return 处理结果
     */
    @Override
    @SneakyThrows
    public byte[] handle(String action, String dbFile, List<String> queries) {
        Pair<Connection, byte[]> result = openConnection(dbFile);
        if (result.getRight() != null) {
            return result.getRight();
        }
        if (TunnelConstants.ACTION_CREATE.equals(action)) {
            return TunnelUtils.getResponse(0, VERSION);
        }
        try (Connection connection = result.getLeft()) {
            if (TunnelConstants.ACTION_VACUUM.equals(action)) {
                execVacuum(connection);
                return TunnelUtils.getResponse(0, VERSION);
            }
            if (TunnelConstants.ACTION_QUERY.equals(action)) {
                return execQuery(queries, connection);
            }
        }
        throw new UnsupportedOperationException("Unknown action: " + action);
    }

    /**
     * 支持的 sql 类型
     */
    @Override
    public SqlType supportType() {
        return SqlType.SQLITE_3;
    }

    private void execVacuum(Connection connection) throws SQLException {
        connection.prepareStatement("VACUUM").executeUpdate();
    }

    private byte[] execQuery(List<String> queries, Connection connection) throws SQLException {
        for (String query : queries) {
            ResultSet result = connection.prepareStatement(query).executeQuery();
            // TODO: 实现这个
        }
        return new byte[0];
    }

    private Pair<Connection, byte[]> openConnection(String dbFile) {
        try {
            Connection connection = DriverManager.getConnection("jdbc:sqlite:" + dbFile);
            return Pair.ofLeft(connection);
        } catch (SQLException e) {
            return Pair.ofRight(TunnelUtils.getResponse(TunnelConstants.ERROR_INVALID_STATUS, e.getMessage()));
        }
    }
}
